using Microsoft.EntityFrameworkCore;
using Order.Api.Write.Dto.Refund;
using Order.Domain.OrderDomain;
using Order.Domain.Enum;
using Order.Interstructrue;
using System;
using System.Threading.Tasks;

namespace Order.Api.Write.Service
{
    /// <summary>
    /// 退款服务实现类
    /// 提供退款状态更新相关的业务逻辑处理
    /// </summary>
    public class RefundService : IRefundService
    {
        private readonly MedicalDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public RefundService(MedicalDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context), "数据库上下文不能为空");
        }

        /// <summary>
        /// 更新退款状态
        /// 支持所有状态变更操作：审批、拒绝、处理等
        /// </summary>
        /// <param name="command">退款状态更新命令</param>
        /// <returns>更新结果</returns>
        public async Task<bool> UpdateRefundStatusAsync(RefundStatusUpdateCommand command)
        {
            try
            {
                // 参数验证
                if (command == null)
                {
                    throw new ArgumentNullException(nameof(command), "状态更新命令不能为空");
                }

                // 查询退款记录
                var refund = await _context.Refund.FirstOrDefaultAsync(x => x.Id == command.RefundId);
                if (refund == null)
                {
                    throw new ArgumentException($"未找到ID为{command.RefundId}的退款记录");
                }

                // 验证状态转换的合法性
                if (!IsValidStatusTransition(refund.RefundStatus, command.TargetStatus))
                {
                    throw new InvalidOperationException($"当前状态{refund.RefundStatus}不允许转换为{command.TargetStatus}");
                }

                // 更新退款信息
                refund.RefundStatus = command.TargetStatus;
                refund.ProcessedTime = DateTime.Now;
                refund.Remark = command.Remark;

                // 保存更改
                await _context.SaveChangesAsync();

                return true;
            }
            catch (DbUpdateException dbEx)
            {
                // 数据库更新异常
                throw new Exception($"数据库更新失败: {dbEx.Message}", dbEx);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                // TODO: 添加日志记录
                throw new Exception($"更新退款状态时发生错误: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 验证状态转换的合法性
        /// </summary>
        /// <param name="currentStatus">当前状态</param>
        /// <param name="targetStatus">目标状态</param>
        /// <returns>是否允许转换</returns>
        private bool IsValidStatusTransition(RefundStatusEnum? currentStatus, RefundStatusEnum targetStatus)
        {
            if (!currentStatus.HasValue)
            {
                return false;
            }

            switch (currentStatus.Value)
            {
                case RefundStatusEnum.待处理:
                    // 待处理状态可以转换为：已完成、已拒绝
                    return targetStatus == RefundStatusEnum.已完成 || targetStatus == RefundStatusEnum.已拒绝;

                case RefundStatusEnum.已完成:
                case RefundStatusEnum.已拒绝:
                    // 已完成和已拒绝状态不允许再转换
                    return false;

                default:
                    return false;
            }
        }
    }
}